import {
  BufferAttribute, BufferGeometry, Color, DoubleSide, Group, Material, Mesh, MeshBasicMaterial, NormalBlending,
  Object3D,
  Points, PointsMaterial, ShaderMaterial,
  SphereBufferGeometry, Sprite, SpriteMaterial, Texture, TextureLoader, Vector3, Line, LineBasicMaterial, CanvasTexture, Raycaster, Vector2, PerspectiveCamera
} from "three";
import earthVertex from '../../shaders/earth/vertex.vs';
import earthFragment from '../../shaders/earth/fragment.fs';
import { createAnimateLine, createLightPillar, createPointMesh, createWaveMesh, getCirclePoints, lon2xyz } from "../Utils/common";
import gsap from "gsap";
import { flyArc } from "../Utils/arc";
const textureLoader = new TextureLoader();
function createSatelliteTexture(color: number): CanvasTexture {
  const canvas = document.createElement('canvas');
  canvas.width = 64;
  canvas.height = 64;
  const context = canvas.getContext('2d');
  if (context) {
    context.clearRect(0, 0, 64, 64);
    context.beginPath();
    context.arc(32, 32, 27, 0, 2 * Math.PI, false);
    context.fillStyle = '#' + color.toString(16).padStart(6, '0');
    context.fill();
    // 添加发光效果
    const gradient = context.createRadialGradient(32, 32, 25, 32, 32, 32);
    gradient.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
    gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.1)');
    gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
    context.beginPath();
    context.arc(32, 32, 32, 0, 2 * Math.PI, false);
    context.fillStyle = gradient;
    context.fill();
  }
  const texture = new CanvasTexture(canvas);
  texture.needsUpdate = true;
  return texture;
}
// 创建卫星状态纹理
const onlineTexture = createSatelliteTexture(0x00FF00);  // 绿色
const offlineTexture = createSatelliteTexture(0xFF0000); // 红色
const alertTexture = createSatelliteTexture(0x808080);   // 灰色
// 卫星状态枚举
export enum SatelliteStatus {
  ONLINE = 'online',
  OFFLINE = 'offline',
  ALERT = 'alert',
  DEGRADED = 'degraded'
}
// 卫星轨道类型
export enum OrbitType {
  LEO = 'leo',  // 低轨道
  MEO = 'meo',  // 中轨道
  GEO = 'geo',  // 地球同步轨道
  SGO = 'sgo'   // 近轨威慑层
}
// 卫星数据类型
export type SatelliteData = {
  id: string;
  name: string;
  orbitType: string;
  status: string;
  position: {
    latitude: number;
    longitude: number;
    altitude: number;
  };
  inclination: number;
  velocity: number;
  launchDate: string;
  subsystems: {
    power: number;
    comm: boolean;
    propulsion: number;
    thermal: number;
  };
  last_update: number;
}
export type punctuation = {
  circleColor: number,
  lightColumn: {
    startColor: number, // 起点颜色
    endColor: number, // 终点颜色
  },
}
// 添加开普勒轨道元素类型定义
type KeplerianOrbit = {
  height: number,             // 轨道高度
  eccentricity_rate: number,  // 偏心率
  semi_major_axis: number,    // 半长轴
  dip: number,                // 倾角
  right_ascension_ascende_node: number, // 升交点赤经
  argument_perigee: number,   // 近地点幅角
  mean_anoma: number          // 平近点角 
}
// 卫星节点数据类型
export type SatelliteNodeData = {
  connectionStatus: number; // 0为离线,1为在线,2为已注入
  satelliteType: number;    // 0为低轨,1为中轨,2为近轨
  satelliteName: string;
  nodeId: string;
  ipAddress: string;
}
// 添加卫星点击事件回调类型定义
export type SatelliteClickCallback = (nodeData: SatelliteNodeData, error?: string) => void;
type options = {
  data: {
    startArray: {
      name: string,
      E: number, // 经度
      N: number, // 维度
    },
    endArray: {
      name: string,
      E: number, // 经度
      N: number, // 维度
    }[]
  }[]
  dom: HTMLElement,
  textures: Record<string, Texture>, // 贴图
  earth: {
    radius: number, // 地球半径
    rotateSpeed: number, // 地球旋转速度
    isRotation: boolean // 地球组是否自转
  }
  satellite: {
    show: boolean, // 是否显示卫星
    rotateSpeed: number, // 旋转速度
    size: number, // 卫星大小
    number: number, // 一个圆环几个球
    count:number //卫星数量
  },
  punctuation: punctuation,
  flyLine: {
    color: number, // 飞线的颜色
    speed: number, // 飞机拖尾线速度
    flyLineColor: number // 飞行线的颜色
  },
  orbits?: KeplerianOrbit[],   // 添加轨道参数数组
  satelliteNodes?: SatelliteNodeData[], // 卫星节点数据
  onSatelliteClick?: SatelliteClickCallback, // 添加卫星点击回调
}
// 轨道层配置
export type OrbitLayerConfig = {
  leo: {
    height: number;       // 轨道高度(km)
    inclination: number;  // 轨道倾角(度)
    count: number;        // 卫星数量
    color: number;        // 轨道颜色
  };
  meo: {
    height: number;
    inclination: number;
    count: number;
    color: number;
  };
  geo: {
    height: number;
    inclination: number;
    count: number;
    color: number;
  };
  sgo: {
    height: number;
    inclination: number;
    count: number;
    color: number;
  };
}

type uniforms = {
  glowColor: { value: Color; }
  scale: { type: string; value: number; }
  bias: { type: string; value: number; }
  power: { type: string; value: number; }
  time: { type: string; value: any; }
  isHover: { value: boolean; };
  map: { value: Texture }
}

export default class earth {

  public group: Group;
  public earthGroup: Group;

  public around: BufferGeometry
  public aroundPoints: Points<BufferGeometry, PointsMaterial>;

  public options: options;
  public uniforms: uniforms
  public timeValue: number;

  public earth: Mesh<SphereBufferGeometry, ShaderMaterial>;
  public punctuationMaterial: MeshBasicMaterial;
  public markupPoint: Group;
  public waveMeshArr: Object3D[];

  public circleLineList: any[];
  public circleList: any[];
  public x: number;
  public n: number;
  public isRotation: boolean;
  public flyLineArcGroup: Group;
  
  // 添加轨道和卫星管理
  public orbitLayers: Group;
  public satellites: Map<string, Sprite>;
  public orbitLines: Map<string, Line>;
  public satellitesByOrbit: Map<string, Sprite[]>;
  public orbitLayerConfig: OrbitLayerConfig;
  
  // 添加声明：轨道色彩映射
  private orbitColorMap: Map<string, number>;
  // 添加声明：卫星状态色彩映射
  private statusColorMap: Map<string, number>;
  // 添加轨道可见性控制
  private orbitVisibility: Map<string, boolean>;

  // 添加basic属性用于访问相机
  public basic: any;

  // 添加射线检测和悬停信息相关属性
  private raycaster: Raycaster;
  private mouse: Vector2;
  private hoveredSatellite: Sprite | null;
  private infoPanel: HTMLElement | null;
  private domElement: HTMLElement;
  
  // 添加点击事件回调
  private onSatelliteClick?: SatelliteClickCallback;

  constructor(options: options) {

    this.options = options;
    this.domElement = options.dom;
    
    // 保存点击回调函数
    this.onSatelliteClick = options.onSatelliteClick;

    this.group = new Group()
    this.group.name = "group";
    this.group.scale.set(0, 0, 0)
    this.earthGroup = new Group()
    this.group.add(this.earthGroup)
    this.earthGroup.name = "EarthGroup";

    // 标注点效果
    this.markupPoint = new Group()
    this.markupPoint.name = "markupPoint"
    this.waveMeshArr = []

    // 卫星和标签
    this.circleLineList = []
    this.circleList = [];
    this.x = 0;
    this.n = 0;

    // 地球自转
    this.isRotation = this.options.earth.isRotation

    // 扫光动画 shader
    this.timeValue = 100
    this.uniforms = {
      glowColor: {
        value: new Color(0x0cd1eb),
      },
      scale: {
        type: "f",
        value: -1.0,
      },
      bias: {
        type: "f",
        value: 1.0,
      },
      power: {
        type: "f",
        value: 3.3,
      },
      time: {
        type: "f",
        value: this.timeValue,
      },
      isHover: {
        value: false,
      },
      map: {
        value: null,
      },
    };
    
    // 初始化轨道和卫星管理
    this.orbitLayers = new Group();
    this.orbitLayers.name = "OrbitLayers";
    this.earthGroup.add(this.orbitLayers);
    this.satellites = new Map();
    this.orbitLines = new Map();
    this.satellitesByOrbit = new Map();
    this.orbitVisibility = new Map();
    // 初始化轨道配置
    this.orbitLayerConfig = {
      leo: {
        height: 600,          // 600km 低轨
        inclination: 35,      // 35度倾角
        count: 80,           // 卫星数量（原来是200，减少到80）
        color:  0x00ffff       // 低轨轨道颜色 #0b7479
      },
      meo: {
        height: 1400,         // 1400km 中轨
        inclination: 60,      // 60度倾角
        count: 30,            // 卫星数量（原来是80，减少到30）
        color: 0xff5588     // 中轨轨道颜色 #6f2c41
      },
      geo: {
        height: 35786,        // 地球同步轨道
        inclination: 0,       // 赤道轨道
        count: 6,             // 卫星数量（保持不变）
        color: 0xffaa00       // 近轨轨道颜色 #dba317
      },
      sgo: {
        height: 35786,        // 静轨威慑层
        inclination: 0,       // 赤道轨道
        count: 8,            // 卫星数量（原来是14，减少到8）
        color: 0xffee00      // 静轨轨道颜色 #dba317
      }
    };
    
    // 初始化轨道颜色映射
  /*   this.orbitColorMap = new Map([
      [OrbitType.LEO, 0x33ffff],   // 更亮的青色
      [OrbitType.MEO, 0xff88bb],   // 更亮的粉红色
      [OrbitType.GEO, 0xffcc33],   // 更亮的橙色
      [OrbitType.SGO, 0xffff33]    // 更亮的类似静轨威慑层颜色
    ]); */
    
    // 初始化卫星状态颜色映射
    this.statusColorMap = new Map([
      [SatelliteStatus.ONLINE, 0x00FF00],    // 在线-绿色
      [SatelliteStatus.OFFLINE, 0xFF0000],   // 离线-红色
      [SatelliteStatus.ALERT, 0xFFFFFF],     // 警告-白色
      [SatelliteStatus.DEGRADED, 0xFFAA00]   // 降级-黄色
    ]);

    // 初始化射线检测和悬停相关属性
    this.raycaster = new Raycaster();
    // 增强射线检测精度
    this.raycaster.params.Sprite = {threshold: 20}; // 增加精灵的检测阈值，从15改为20
    this.raycaster.params.Points = {threshold: 5};
    this.raycaster.params.Line = {threshold: 5};
    
    this.mouse = new Vector2();
    this.hoveredSatellite = null;
    this.infoPanel = null;
    
    // 添加鼠标移动事件监听
    this.initMouseEventListeners();
  }

  async init(): Promise<void> {
    return new Promise(async (resolve) => {
      this.createEarth(); // 创建地球
      this.createStars(); // 添加星星
      this.createEarthGlow() // 创建地球辉光
      this.createEarthAperture() // 创建地球的大气层
      await this.createMarkupPoint() // 创建柱状点位
      await this.createSpriteLabel() // 创建标签
      // this.createAnimateCircle() // 创建环绕卫星
      // this.createFlyLine() // 创建飞线  
      // 创建卫星轨道层
      this.createOrbitLayers();
      
      // 创建卫星节点
      if (this.options.satelliteNodes && this.options.satelliteNodes.length > 0) {
        this.createSatelliteNodes();
      }
      
      this.show()
      resolve()
    })
  }

  createEarth() {
    const earth_geometry = new SphereBufferGeometry(
      this.options.earth.radius,
      60,
      60
    );
    const earth_border = new SphereBufferGeometry(
      this.options.earth.radius + 10,
      60,
      60
    );

    const pointMaterial = new PointsMaterial({
      color: 0x81ffff, //设置颜色，默认 0xFFFFFF
      transparent: true,
      sizeAttenuation: true,
      opacity: 0.1,
      vertexColors: false, //定义材料是否使用顶点颜色，默认false ---如果该选项设置为true，则color属性失效
      size: 0.01, //定义粒子的大小。默认为1.0
    })
    const points = new Points(earth_border, pointMaterial); //将模型添加到场景
    this.earthGroup.add(points);
    this.uniforms.map.value = this.options.textures.earth;
    const earth_material = new ShaderMaterial({
      // wireframe:true, // 显示模型线条
      uniforms: this.uniforms,
      vertexShader: earthVertex,
      fragmentShader: earthFragment,
    });
    earth_material.needsUpdate = true;
    this.earth = new Mesh(earth_geometry, earth_material);
    this.earth.name = "earth";
    this.earthGroup.add(this.earth);
  }

  createStars() {
    const vertices = []
    const colors = []
    for (let i = 0; i < 500; i++) {
      const vertex = new Vector3();
      vertex.x = 800 * Math.random() - 300;
      vertex.y = 800 * Math.random() - 300;
      vertex.z = 800 * Math.random() - 300;
      vertices.push(vertex.x, vertex.y, vertex.z);
      colors.push(new Color(1, 1, 1));
    }
    // 星空效果
    this.around = new BufferGeometry()
    this.around.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
    this.around.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
    const aroundMaterial = new PointsMaterial({
      size: 2,
      sizeAttenuation: true, // 尺寸衰减
      color: 0x4d76cf,
      transparent: true,
      opacity: 1,
      map: this.options.textures.gradient,
    });

    this.aroundPoints = new Points(this.around, aroundMaterial);
    this.aroundPoints.name = "星空";
    this.aroundPoints.scale.set(1, 1, 1);
    this.group.add(this.aroundPoints);
  }

  createEarthGlow() {
    const R = this.options.earth.radius; //地球半径

    // TextureLoader创建一个纹理加载器对象，可以加载图片作为纹理贴图
    const texture = this.options.textures.glow; // 加载纹理贴图

    // 创建精灵材质对象SpriteMaterial
    const spriteMaterial = new SpriteMaterial({
      map: texture, // 设置精灵纹理贴图
      color: 0x4390d1,
      transparent: true, //开启透明
      opacity: 0.7, // 可以通过透明度整体调节光圈
      depthWrite: false, //禁止写入深度缓冲区数据
    });

    // 创建表示地球光圈的精灵模型
    const sprite = new Sprite(spriteMaterial);
    sprite.scale.set(R * 3.0, R * 3.0, 1); //适当缩放精灵
    this.earthGroup.add(sprite);
  }

  createEarthAperture() {

    const vertexShader = [
      "varying vec3	vVertexWorldPosition;",
      "varying vec3	vVertexNormal;",
      "varying vec4	vFragColor;",
      "void main(){",
      "	vVertexNormal	= normalize(normalMatrix * normal);", //将法线转换到视图坐标系中
      "	vVertexWorldPosition	= (modelMatrix * vec4(position, 1.0)).xyz;", //将顶点转换到世界坐标系中
      "	// set gl_Position",
      "	gl_Position	= projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
      "}",
    ].join("\n");

    //大气层效果
    const AeroSphere = {
      uniforms: {
        coeficient: {
          type: "f",
          value: 1.0,
        },
        power: {
          type: "f",
          value: 3,
        },
        glowColor: {
          type: "c",
          value: new Color(0x4390d1),
        },
      },
      vertexShader: vertexShader,
      fragmentShader: [
        "uniform vec3	glowColor;",
        "uniform float	coeficient;",
        "uniform float	power;",

        "varying vec3	vVertexNormal;",
        "varying vec3	vVertexWorldPosition;",

        "varying vec4	vFragColor;",

        "void main(){",
        "	vec3 worldCameraToVertex = vVertexWorldPosition - cameraPosition;", //世界坐标系中从相机位置到顶点位置的距离
        "	vec3 viewCameraToVertex	= (viewMatrix * vec4(worldCameraToVertex, 0.0)).xyz;", //视图坐标系中从相机位置到顶点位置的距离
        "	viewCameraToVertex= normalize(viewCameraToVertex);", //规一化
        "	float intensity	= pow(coeficient + dot(vVertexNormal, viewCameraToVertex), power);",
        "	gl_FragColor = vec4(glowColor, intensity);",
        "}",
      ].join("\n"),
    };
    //球体 辉光 大气层
    const material1 = new ShaderMaterial({
      uniforms: AeroSphere.uniforms,
      vertexShader: AeroSphere.vertexShader,
      fragmentShader: AeroSphere.fragmentShader,
      blending: NormalBlending,
      transparent: true,
      depthWrite: false,
    });
    const sphere = new SphereBufferGeometry(
      this.options.earth.radius + 0,
      50,
      50
    );
    const mesh = new Mesh(sphere, material1);
    this.earthGroup.add(mesh);
  }

  async createMarkupPoint() {

    await Promise.all(this.options.data.map(async (item) => {

      const radius = this.options.earth.radius;
      this.punctuationMaterial = new MeshBasicMaterial({
        color: this.options.punctuation.circleColor,
        map: this.options.textures.label,
        transparent: true, //使用背景透明的png贴图，注意开启透明计算
        depthWrite: false, //禁止写入深度缓冲区数据
      });

      await Promise.all(item.endArray.map((obj) => {
        const lon = obj.E; //经度
        const lat = obj.N; //纬度
        const mesh = createPointMesh({ radius, lon, lat, material: this.punctuationMaterial }); //光柱底座矩形平面
        this.markupPoint.add(mesh);
        const LightPillar = createLightPillar({
          radius: this.options.earth.radius,
          lon,
          lat,
          index: 1,
          textures: this.options.textures,
          punctuation: this.options.punctuation
        }); //光柱
        this.markupPoint.add(LightPillar);
        const WaveMesh = createWaveMesh({ radius, lon, lat, textures: this.options.textures }); //波动光圈
        this.markupPoint.add(WaveMesh);
        this.waveMeshArr.push(WaveMesh);
      }))
      this.earthGroup.add(this.markupPoint)
    }))
  }



  async createSpriteLabel() {
    /* await Promise.all(this.options.data.map(async item => {
      let cityArry: { name: string; E: number; N: number }[] = [];
      cityArry = cityArry.concat(...item.endArray);
      await Promise.all(cityArry.map(async e => {
        const p = lon2xyz(this.options.earth.radius * 1.001, e.E, e.N);    
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        // 计算文本宽度以确定画布尺寸
        ctx.font = 'bold 20px Arial';
        const textMetrics = ctx.measureText(e.name);
        const textWidth = Math.max(textMetrics.width + 16, 50); // 最小宽度50px
        // 设置画布大小
        canvas.width = textWidth;
        canvas.height = 40; // 适应文本高度
        // 绘制背景
        ctx.fillStyle = 'rgba(40, 108, 181, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);  
        // 绘制顶部边框
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(canvas.width, 0);
        ctx.lineWidth = 3;
        ctx.strokeStyle = '#0cd1eb';
        ctx.stroke();        
        // 绘制文本
        ctx.font = 'bold 20px Arial';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(e.name, canvas.width / 2, canvas.height / 2);
        // 创建贴图
        const texture = new Texture(canvas);
        texture.needsUpdate = true;
  
        const material = new SpriteMaterial({
          map: texture,
          transparent: true,
        });
        const sprite = new Sprite(material);
        // 根据画布实际大小设置精灵大小
        const scaleX = textWidth / 20; // 调整这个比例以适应你的场景
        sprite.scale.set(scaleX, 2, 1);
        sprite.position.set(p.x * 1.1, p.y * 1.1, p.z * 1.1);
        this.earth.add(sprite);
      }))
    })) */
  }

  createAnimateCircle() {
    // 检查是否有轨道参数
    if (!this.options.orbits || this.options.orbits.length === 0) {
      console.warn("没有轨道参数，使用默认轨道");
      
      return;
    }
    // 创建卫星材质
    const satelliteMaterial = new SpriteMaterial({
      map: onlineTexture,
      color: 0xffffff,
    });
    
    const bigList = [15, 15, 1]; // 卫星大小
    // 轨道材质
    const orbitMaterial = new MeshBasicMaterial({
      color: 0x4390d1, // 使用更明显的颜色
      transparent: true,
      opacity: 0.6,
      side: DoubleSide,
    });   
    // 为每个轨道创建一条线和卫星
    this.options.orbits.forEach((orbit, index) => {
      // 计算轨道上的点
      const orbitPoints = this.calculateOrbitPoints(orbit, 200); 
      // 创建轨道线
      const orbitGeometry = new BufferGeometry();
      const positions: number[] = [];
      orbitPoints.forEach(point => {
        positions.push(point.x, point.y, point.z);
      });
      
      orbitGeometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
      // 创建线条
      const orbitLine = new Line(orbitGeometry, orbitMaterial);
      this.earthGroup.add(orbitLine);
      this.circleLineList.push(orbitLine);
      // 创建卫星
      const satellite = new Sprite(satelliteMaterial);
      satellite.scale.set(...bigList);
      
      // 设置卫星初始位置
      satellite.position.copy(orbitPoints[0]);
      this.earthGroup.add(satellite);
      
      // 存储卫星和轨道信息
      orbitLine.userData = {
        orbit: orbit,
        satellite: satellite,
        time: 0,
        points: orbitPoints
      };
    });
  }

  createFlyLine() {

    this.flyLineArcGroup = new Group();
    this.flyLineArcGroup.userData['flyLineArray'] = []
    this.earthGroup.add(this.flyLineArcGroup)

    this.options.data.forEach((cities) => {
      cities.endArray.forEach(item => {

        // 调用函数flyArc绘制球面上任意两点之间飞线圆弧轨迹
        const arcline = flyArc(
          this.options.earth.radius,
          cities.startArray.E,
          cities.startArray.N,
          item.E,
          item.N,
          this.options.flyLine
        );

        this.flyLineArcGroup.add(arcline); // 飞线插入flyArcGroup中
        this.flyLineArcGroup.userData['flyLineArray'].push(arcline.userData['flyLine'])
      });

    })

  }

  show() {
    gsap.to(this.group.scale, {
      x: 1,
      y: 1,
      z: 1,
      duration: 2,
      ease: "Quadratic",
    })
  }

  render() {
    this.flyLineArcGroup?.userData['flyLineArray']?.forEach(fly => {
      fly.rotation.z += this.options.flyLine.speed; // 调节飞线速度
      if (fly.rotation.z >= fly.flyEndAngle) fly.rotation.z = 0;
    })
    if (this.isRotation) {
      this.earthGroup.rotation.y += this.options.earth.rotateSpeed;
    }
    this.uniforms.time.value =
      this.uniforms.time.value < -this.timeValue
        ? this.timeValue
        : this.uniforms.time.value - 1;

    if (this.waveMeshArr.length) {
      this.waveMeshArr.forEach((mesh: Mesh) => {
        mesh.userData['scale'] += 0.007;
        mesh.scale.set(
          mesh.userData['size'] * mesh.userData['scale'],
          mesh.userData['size'] * mesh.userData['scale'],
          mesh.userData['size'] * mesh.userData['scale']
        );
        if (mesh.userData['scale'] <= 1.5) {
          (mesh.material as Material).opacity = (mesh.userData['scale'] - 1) * 2; //2等于1/(1.5-1.0)，保证透明度在0~1之间变化
        } else if (mesh.userData['scale'] > 1.5 && mesh.userData['scale'] <= 2) {
          (mesh.material as Material).opacity = 1 - (mesh.userData['scale'] - 1.5) * 2; //2等于1/(2.0-1.5) mesh缩放2倍对应0 缩放1.5被对应1
        } else {
          mesh.userData['scale'] = 1;
        }
      });
    }
    
    // 更新轨道上的卫星自动运动
    this.satellites.forEach(satellite => {
      const orbitPoints = satellite.userData.orbitPoints;
      if (!orbitPoints) return;
      
      // 获取卫星当前位置索引
      let pointIndex = satellite.userData.currentPointIndex || 0;
      
      // 根据卫星轨道类型调整自动移动速度
      const orbitType = satellite.userData.orbitType;
      // 减小速度因子使运动更平滑
      const speedFactor = orbitType === OrbitType.LEO ? 0.08 :  // 从0.1减少到0.05
                         orbitType === OrbitType.MEO ? 0.08 :   // 从0.02减少到0.01
                         0.08;                                // 从0.02减少到0.005
      
      // 更新位置索引
      pointIndex = (pointIndex + speedFactor) % orbitPoints.length;
      satellite.userData.currentPointIndex = pointIndex;
      
      // 更新卫星位置 - 使用插值计算更平滑的位置
      const floorIndex = Math.floor(pointIndex);
      const nextIndex = (floorIndex + 1) % orbitPoints.length;
      const fraction = pointIndex - floorIndex;
      
      // 当前点和下一个点
      const currentPosition = orbitPoints[floorIndex];
      const nextPosition = orbitPoints[nextIndex];
      
      // 插值计算新位置
      const newX = currentPosition.x + (nextPosition.x - currentPosition.x) * fraction;
      const newY = currentPosition.y + (nextPosition.y - currentPosition.y) * fraction;
      const newZ = currentPosition.z + (nextPosition.z - currentPosition.z) * fraction;
      
      // 设置卫星位置
      satellite.position.set(newX, newY, newZ);
    });
  }

  // 添加计算轨道点的方法
  calculateOrbitPoints(orbit: KeplerianOrbit, pointCount: number = 200): Vector3[] {
    const points: Vector3[] = [];
    const earthRadius = this.options.earth.radius;
    // 转换角度为弧度
    const inclination = orbit.dip * Math.PI / 180;
    const raan = orbit.right_ascension_ascende_node * Math.PI / 180;
    const argPeriapsis = orbit.argument_perigee * Math.PI / 180;
    const e = orbit.eccentricity_rate;
    // 调整半长轴缩放，使轨道可见
    const a = earthRadius * 1.5; // 使用固定大小，确保可见性
    // 计算轨道上的点
    for (let i = 0; i < pointCount; i++) {
      // 真近点角
      const trueAnomaly = (i / pointCount) * 2 * Math.PI;   
      // 计算轨道平面上的位置 (极坐标)
      const r = a * (1 - e * e) / (1 + e * Math.cos(trueAnomaly));  
      // 转换为笛卡尔坐标 (轨道平面)
      const x = r * Math.cos(trueAnomaly);
      const y = r * Math.sin(trueAnomaly); 
      // 应用轨道倾角、升交点赤经和近地点幅角的旋转
      // 先绕x轴旋转(倾角)
      let xRot = x;
      let yRot = y * Math.cos(inclination);
      let zRot = y * Math.sin(inclination);
      // 再绕z轴旋转(升交点赤经)
      const xFinal = xRot * Math.cos(raan) - yRot * Math.sin(raan);
      const yFinal = xRot * Math.sin(raan) + yRot * Math.cos(raan);
      const zFinal = zRot;
      // 再绕z轴旋转(近地点幅角)
      const xFinal2 = xFinal * Math.cos(argPeriapsis) - yFinal * Math.sin(argPeriapsis);
      const yFinal2 = xFinal * Math.sin(argPeriapsis) + yFinal * Math.cos(argPeriapsis);
      points.push(new Vector3(xFinal2, zFinal, yFinal2));
    }
    return points;
  }

  // 创建卫星轨道层
  createOrbitLayers() {
    // 按照需求文档创建三层卫星轨道
    
    // 1. 低轨突击层 (600km/35°)
    this.createOrbitLayer(OrbitType.LEO, this.orbitLayerConfig.leo);
    
    // 2. 中轨警戒层 (1400km/60°)
    this.createOrbitLayer(OrbitType.MEO, this.orbitLayerConfig.meo);
    
    // 3. 静轨威慑层 (35786km/0°)
    this.createOrbitLayer(OrbitType.GEO, this.orbitLayerConfig.geo);
    
    // 4. 战略静止轨道 (稍高于GEO)
    this.createOrbitLayer(OrbitType.SGO, this.orbitLayerConfig.sgo);
    
    // 默认所有轨道可见
    this.orbitVisibility.set(OrbitType.LEO, true);
    this.orbitVisibility.set(OrbitType.MEO, true);
    this.orbitVisibility.set(OrbitType.GEO, true);
    this.orbitVisibility.set(OrbitType.SGO, true);
  }
  
  // 创建单个轨道层
  createOrbitLayer(orbitType: string, config: {height: number, inclination: number, count: number, color: number}) {
    // 创建轨道层组
    const layerGroup = new Group();
    layerGroup.name = `${orbitType}Layer`;
    this.orbitLayers.add(layerGroup);
    
    // 按照轨道面数量创建轨道
    const planesCount = orbitType === OrbitType.LEO ? 12 : 
                       orbitType === OrbitType.MEO ? 6 :
                       orbitType === OrbitType.GEO ? 1 : 2;
    
    const satellitesPerPlane = Math.floor(config.count / planesCount);
    
    // 初始化轨道组列表
    this.satellitesByOrbit.set(orbitType, []);
    
    // 创建每个轨道平面
    for (let i = 0; i < planesCount; i++) {
      // 计算升交点赤经 (使轨道均匀分布)
      const raan = (i * 360 / planesCount) * Math.PI / 180;
      
      // 调整地球半径比例尺
      const earthRadius = this.options.earth.radius;
      // 计算轨道半径 (按比例缩放)
      const scaleFactor = orbitType === OrbitType.LEO ? 0.15 : 
                         orbitType === OrbitType.MEO ? 0.3 :
                         0.8; // GEO和SGO使用相同比例
      
      const orbitRadius = earthRadius * (1 + scaleFactor);
      
      // 创建轨道
      this.createOrbit(
        orbitType,
        `${orbitType}-plane-${i}`,
        orbitRadius,
        config.inclination,
        raan,
        config.color,
        satellitesPerPlane
      );
    }
  }
  
  // 创建单个轨道
  createOrbit(orbitType: string, orbitId: string, radius: number, inclination: number, raan: number, color: number, satelliteCount: number) {
    // 创建轨道点
    const points: Vector3[] = [];
    const segments = 100;
    
    for (let i = 0; i <= segments; i++) {
      const theta = (i / segments) * Math.PI * 2;
      
      // 轨道平面上的点
      let x = radius * Math.cos(theta);
      let y = 0;
      let z = radius * Math.sin(theta);
      
      // 应用轨道倾角
      const incRad = inclination * Math.PI / 180;
      const y2 = y * Math.cos(incRad) - z * Math.sin(incRad);
      const z2 = y * Math.sin(incRad) + z * Math.cos(incRad);
      y = y2;
      z = z2;
      
      // 应用升交点赤经
      const x3 = x * Math.cos(raan) - z * Math.sin(raan);
      const z3 = x * Math.sin(raan) + z * Math.cos(raan);
      x = x3;
      z = z3;
      
      points.push(new Vector3(x, y, z));
    }
    
    // 创建轨道线几何体
    const orbitGeometry = new BufferGeometry();
    orbitGeometry.setFromPoints(points);
    
    // 创建轨道线材质
    const orbitMaterial = new LineBasicMaterial({
      color: color,
      transparent: true,
      opacity: 1,
      linewidth: 10
    });
    
    // 创建轨道线
    const orbitLine = new Line(orbitGeometry, orbitMaterial);
    orbitLine.name = orbitId;
    this.orbitLayers.add(orbitLine);
    this.orbitLines.set(orbitId, orbitLine);

    return orbitLine;
  }
  
  
  
  
  /**
   * 设置轨道层的可见性
   * @param orbitType 轨道类型 
   * @param visible 是否可见
   */
  setOrbitVisibility(orbitType: string, visible: boolean) {
    // 更新轨道可见性状态
    this.orbitVisibility.set(orbitType, visible);
    
    // 更新轨道线可见性
    this.orbitLines.forEach((line, id) => {
      if (id.startsWith(orbitType)) {
        line.visible = visible;
      }
    });
    
    // 更新卫星可见性
    this.satellites.forEach((satellite, id) => {
      if (satellite.userData.orbitType === orbitType) {
        satellite.visible = visible;
      }
    });
  }
  
  /**
   * 显示特定的轨道层，隐藏其他层
   * @param orbitType 要显示的轨道类型，如果为空则显示所有轨道
   */
  showOrbitLayer(orbitType?: string) {
    if (!orbitType) {
      // 显示所有轨道
      this.setOrbitVisibility(OrbitType.LEO, true);
      this.setOrbitVisibility(OrbitType.MEO, true);
      this.setOrbitVisibility(OrbitType.GEO, true);
      this.setOrbitVisibility(OrbitType.SGO, true);
    } else {
      // 隐藏所有轨道
      this.setOrbitVisibility(OrbitType.LEO, false);
      this.setOrbitVisibility(OrbitType.MEO, false);
      this.setOrbitVisibility(OrbitType.GEO, false);
      this.setOrbitVisibility(OrbitType.SGO, false);    
      // 只显示指定轨道
      this.setOrbitVisibility(orbitType, true);
    }
  }
  
  // 创建卫星节点方法
  createSatelliteNodes() {
    if (!this.options.satelliteNodes) return;
    
    // 遍历卫星节点数据
    this.options.satelliteNodes.forEach((node, index) => {
      // 根据卫星类型确定轨道类型
      let orbitType = '';
      switch (node.satelliteType) {
        case 0: // 低轨
          orbitType = OrbitType.LEO;
          break;
        case 1: // 中轨
          orbitType = OrbitType.MEO;
          break;
        case 2: // 近轨/静轨
          orbitType = OrbitType.GEO;
          break;
        default:
          orbitType = OrbitType.LEO;
      }
      
      // 根据连接状态确定卫星状态
      let satelliteStatus = '';
      switch (node.connectionStatus) {
        case 0: // 离线
          satelliteStatus = SatelliteStatus.OFFLINE;
          break;
        case 1: // 在线
          satelliteStatus = SatelliteStatus.ONLINE;
          break;
        case 2: // 已注入（警告状态）
          satelliteStatus = SatelliteStatus.ALERT;
          break;
        default:
          satelliteStatus = SatelliteStatus.OFFLINE;
      }
      
      // 创建卫星节点
      this.createSatelliteNode(
        node.nodeId,
        node.satelliteName,
        orbitType,
        satelliteStatus,
        node.ipAddress,
        index
      );
    });
  }
  
  // 创建单个卫星节点
  createSatelliteNode(id: string, name: string, orbitType: string, status: string, ipAddress: string, index: number) {
    // 确保卫星ID是有效的
    if (!id) {
      console.error("创建卫星节点时ID无效:", id);
      return null;
    }
    
    // 根据轨道类型选择对应轨道的点
    const orbitLinesList = Array.from(this.orbitLines.entries())
      .filter(([key]) => key.startsWith(orbitType))
      .map(([_, line]) => line);
    
    if (orbitLinesList.length === 0) {
      console.error(`找不到${orbitType}类型的轨道线`);
      return null;
    }
    
    // 选择一条轨道
    const orbitLine = orbitLinesList[index % orbitLinesList.length];
    
    // 获取轨道上的点
    const orbitPoints = Array.from(orbitLine.geometry.attributes.position.array);
    const points: Vector3[] = [];
    
    // 将数组转换为Vector3点
    for (let i = 0; i < orbitPoints.length; i += 3) {
      points.push(new Vector3(orbitPoints[i], orbitPoints[i+1], orbitPoints[i+2]));
    }
    
    // 根据卫星状态选择纹理
    let texture;
    switch (status) {
      case SatelliteStatus.ONLINE:
        texture = onlineTexture;
        break;
      case SatelliteStatus.OFFLINE:
        texture = offlineTexture;
        break;
      case SatelliteStatus.ALERT:
        texture = alertTexture;
        break;
      default:
        texture = offlineTexture;
    }
    
    // 创建卫星精灵
    const satelliteMaterial = new SpriteMaterial({
      map: texture,
      color: 0xffffff,
    });
    
    const satellite = new Sprite(satelliteMaterial);
    
    // 设置卫星大小（根据轨道类型调整）
    const sizeMultiplier = orbitType === OrbitType.LEO ? 3 :
                          orbitType === OrbitType.MEO ? 3 : 3;
    satellite.scale.set(
      this.options.satellite.size * sizeMultiplier,
      this.options.satellite.size * sizeMultiplier,
      this.options.satellite.size * sizeMultiplier
    );
    
    // 增强卫星精灵的可点击性
    satellite.matrixAutoUpdate = true;
    satellite.renderOrder = 10; // 确保精灵渲染在前面，更容易点击
    satellite.userData.isClickable = true; // 添加标记，表示可点击
    
    // 设置卫星初始位置 - 在轨道上均匀分布
    const startingPointIndex = Math.floor((points.length / Math.max(this.options.satelliteNodes?.length || 1, 1)) * index) % points.length;
    satellite.position.copy(points[startingPointIndex]);
    
    // 给每个卫星增加唯一标识
    satellite.name = `satellite-${id}`;
    
    // 存储卫星信息
    satellite.userData = {
      id,                     // 使用传入的ID，确保不变
      name,                   // 保存原始名称
      orbitType,              // 保存轨道类型
      status,                 // 保存状态
      ipAddress,              // 保存IP地址
      orbitPoints: points,    // 保存轨道点
      currentPointIndex: startingPointIndex,  // 保存当前位置索引
      initialIndex: index     // 保存初始索引，用于排查问题
    };
    
    // 添加到场景并保存到卫星列表
    this.orbitLayers.add(satellite);
    
    // 确保ID是唯一的，如果已存在则移除旧的
    if (this.satellites.has(id)) {
      console.warn(`卫星ID ${id} 已存在，将被覆盖`);
      const oldSatellite = this.satellites.get(id);
      if (oldSatellite) {
        this.orbitLayers.remove(oldSatellite);
      }
    }
    
    // 保存到卫星映射表
    this.satellites.set(id, satellite);
    
    // 添加到卫星轨道分组
    if (!this.satellitesByOrbit.has(orbitType)) {
      this.satellitesByOrbit.set(orbitType, []);
    }
    
    // 确保不重复添加到轨道组
    const orbitSatellites = this.satellitesByOrbit.get(orbitType);
    if (orbitSatellites && !orbitSatellites.includes(satellite)) {
      orbitSatellites.push(satellite);
    }
    return satellite;
  }

  // 初始化鼠标事件监听
  private initMouseEventListeners() {
    // 鼠标移动事件
    this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this));
    
    // 添加鼠标点击事件
    this.domElement.addEventListener('click', this.onMouseClick.bind(this));
    
    // 监听窗口大小变化，确保信息面板位置正确
    window.addEventListener('resize', () => {
      if (this.hoveredSatellite && this.infoPanel) {
        this.updateInfoPanelPosition(this.hoveredSatellite);
      }
    });
  }
  
  // 鼠标移动事件处理
  private onMouseMove(event: MouseEvent) {
    // 计算鼠标在归一化设备坐标中的位置
    const rect = this.domElement.getBoundingClientRect();
    this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    
    // 执行射线检测
    this.checkSatelliteHover();
  }
  
  // 检测卫星悬停
  private checkSatelliteHover() {
    // 设置射线投射方向
    this.raycaster.setFromCamera(this.mouse, this.basic?.camera); 
    // 获取所有卫星对象用于射线检测
    const satelliteObjects = Array.from(this.satellites.values());
    // 执行射线检测
    const intersects = this.raycaster.intersectObjects(satelliteObjects, true);
    // 如果有交叉，则显示第一个卫星的信息
    if (intersects.length > 0) {
      const satellite = intersects[0].object as Sprite; 
      // 如果当前悬停的卫星与之前不同，则更新信息面板
      if (this.hoveredSatellite !== satellite) {
        this.hoveredSatellite = satellite;
        this.showSatelliteInfo(satellite);
      }
    } else {
      // 如果没有交叉，并且之前有悬停的卫星，则隐藏信息面板
      if (this.hoveredSatellite) {
        this.hideInfoPanel();
        this.hoveredSatellite = null;
      }
    }
  }
  // 显示卫星信息
  private showSatelliteInfo(satellite: Sprite) {
    // 创建或更新信息面板
    if (!this.infoPanel) {
      this.createInfoPanel();
    } 
    if (this.infoPanel) {
      // 获取卫星数据
      const satelliteData = satellite.userData; 
 
      
      // 获取状态文本
      let statusText = '';
      switch (satelliteData.status) {
        case SatelliteStatus.ONLINE:
          statusText = '在线';
          break;
        case SatelliteStatus.OFFLINE:
          statusText = '离线';
          break;
        case SatelliteStatus.ALERT:
          statusText = '已注入';
          break;
        default:
          statusText = '未知';
      }
      
      // 获取轨道类型文本
      let orbitTypeText = '';
      switch (satelliteData.orbitType) {
        case OrbitType.LEO:
          orbitTypeText = '低轨道';
          break;
        case OrbitType.MEO:
          orbitTypeText = '中轨道';
          break;
        case OrbitType.GEO:
          orbitTypeText = '近轨道';
          break;
        case OrbitType.SGO:
          orbitTypeText = '静轨威慑层';
          break;
        default:
          orbitTypeText = '未知';
      }
      
      // 更新信息面板内容
      this.infoPanel.innerHTML = `
        <div class="satellite-info-header">${satelliteData.name}</div>
        <div class="satellite-info-content">
          <div class="satellite-info-item">
            <span class="label">节点ID:</span>
            <span class="value">${satelliteData.id}</span>
          </div>
          <div class="satellite-info-item">
            <span class="label">状态:</span>
            <span class="value">${statusText}</span>
          </div>
          <div class="satellite-info-item">
            <span class="label">轨道类型:</span>
            <span class="value">${orbitTypeText}</span>
          </div>
          <div class="satellite-info-item">
            <span class="label">IP地址:</span>
            <span class="value">${satelliteData.ipAddress}</span>
          </div>
        </div>
      `;
      
      // 更新面板位置
      this.updateInfoPanelPosition(satellite);
      // 显示面板
      this.infoPanel.style.display = 'block';
    }
  }
  
  // 创建信息面板
  private createInfoPanel() {
    const panel = document.createElement('div');
    panel.className = 'satellite-info-panel';
    // 设置面板样式
    panel.style.position = 'absolute';
    panel.style.backgroundColor = 'rgba(0, 20, 40, 0.8)';
    panel.style.border = '1px solid #0cd1eb';
    panel.style.borderTop = '3px solid #0cd1eb';
    panel.style.borderRadius = '2px';
    panel.style.color = 'white';
    panel.style.padding = '10px';
    panel.style.fontSize = '14px';
    panel.style.fontFamily = 'Arial, sans-serif';
    panel.style.zIndex = '1000';
    panel.style.pointerEvents = 'none'; // 防止面板阻挡鼠标事件
    panel.style.minWidth = '200px';
    panel.style.backdropFilter = 'blur(5px)';
    panel.style.boxShadow = '0 0 10px rgba(12, 209, 235, 0.5)';
    
    // 添加到DOM
    this.domElement.parentNode?.appendChild(panel);
    this.infoPanel = panel;
    
    // 添加内部样式
    const style = document.createElement('style');
    style.textContent = `
      .satellite-info-header {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 8px;
        color: #0cd1eb;
      }
      .satellite-info-content {
        display: flex;
        flex-direction: column;
        gap: 5px;
      }
      .satellite-info-item {
        display: flex;
        justify-content: space-between;
      }
      .satellite-info-item .label {
        color: #999;
        margin-right: 10px;
      }
      .satellite-info-item .value {
        color: white;
      }
    `;
    document.head.appendChild(style);
  }
  
  // 更新信息面板位置
  private updateInfoPanelPosition(satellite: Sprite) {
    if (!this.infoPanel) return;
    
    // 将3D物体坐标转换为屏幕坐标
    const position = new Vector3();
    satellite.getWorldPosition(position);
    
    const camera = this.basic?.camera;
    const width = this.domElement.clientWidth;
    const height = this.domElement.clientHeight;
    
    position.project(camera);
    
    const x = (position.x * 0.5 + 0.5) * width;
    const y = (-position.y * 0.5 + 0.5) * height;
    
    // 调整面板位置，避免超出视图边界
    const panelWidth = this.infoPanel.offsetWidth;
    const panelHeight = this.infoPanel.offsetHeight;
    
    let left = x + 15;
    let top = y - panelHeight / 2;
    
    // 确保面板不超出右边界
    if (left + panelWidth > width) {
      left = x - panelWidth - 15;
    }
    
    // 确保面板不超出上下边界
    if (top < 0) {
      top = 0;
    } else if (top + panelHeight > height) {
      top = height - panelHeight;
    }
    
    // 设置面板位置
    this.infoPanel.style.left = `${left}px`;
    this.infoPanel.style.top = `${top}px`;
  }
  
  // 隐藏信息面板
  private hideInfoPanel() {
    if (this.infoPanel) {
      this.infoPanel.style.display = 'none';
    }
  }
  
  // 添加鼠标点击事件处理
  private onMouseClick(event: MouseEvent) {
    // 如果没有设置点击回调，则不处理
    if (!this.onSatelliteClick) {
      console.log("未设置点击回调函数");
      return;
    }
    
    // 计算鼠标在归一化设备坐标中的位置
    const rect = this.domElement.getBoundingClientRect();
    this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    
    console.log("点击位置坐标:", this.mouse.x, this.mouse.y);
    
    // 检查basic和camera是否存在
    if (!this.basic || !this.basic.camera) {
      console.error("相机不存在");
      return;
    }
    
    // 使用与checkSatelliteHover相同的检测逻辑
    this.raycaster.setFromCamera(this.mouse, this.basic.camera);
    const satelliteObjects = Array.from(this.satellites.values());
    const intersects = this.raycaster.intersectObjects(satelliteObjects, true);
    
    if (intersects.length > 0) {
      const clickedSatellite = intersects[0].object as Sprite;
      console.log("点击到的卫星:", clickedSatellite.name);
      
      // 直接使用点击到的卫星对象创建节点数据
      if (clickedSatellite && clickedSatellite.userData) {
        try {
          // 构建节点数据
          const nodeData: SatelliteNodeData = {
            connectionStatus: this.getConnectionStatusFromSatelliteStatus(clickedSatellite.userData.status),
            satelliteType: this.getSatelliteTypeFromOrbitType(clickedSatellite.userData.orbitType),
            satelliteName: clickedSatellite.userData.name,
            nodeId: clickedSatellite.userData.id,
            ipAddress: clickedSatellite.userData.ipAddress || ''
          };
          
          console.log("将要传递的节点数据:", nodeData);
          
          // 调用回调函数
          this.onSatelliteClick(nodeData);
        } catch (error) {
          console.error("处理卫星点击事件出错:", error);
          
          // 尝试从Map中重新获取卫星数据
          const satelliteId = clickedSatellite.userData?.id;
          if (satelliteId && this.satellites.has(satelliteId)) {
            const satellite = this.satellites.get(satelliteId);
            if (satellite && satellite.userData) {
              const nodeData: SatelliteNodeData = {
                connectionStatus: this.getConnectionStatusFromSatelliteStatus(satellite.userData.status),
                satelliteType: this.getSatelliteTypeFromOrbitType(satellite.userData.orbitType),
                satelliteName: satellite.userData.name,
                nodeId: satellite.userData.id,
                ipAddress: satellite.userData.ipAddress || ''
              };
              
              console.log("备用方法 - 将要传递的节点数据:", nodeData);
              this.onSatelliteClick(nodeData);
            }
          }
        }
      }
    } else {
      const msg = "未点击到卫星";
      // 创建一个空的卫星节点数据
      const emptyNodeData: SatelliteNodeData = {
        connectionStatus: 0,
        satelliteType: 0,
        satelliteName: '',
        nodeId: '',
        ipAddress: ''
      };
      this.onSatelliteClick(emptyNodeData, msg);
    }
  }
  
  // 辅助方法：从卫星状态获取连接状态
  private getConnectionStatusFromSatelliteStatus(status: string): number {
    switch (status) {
      case SatelliteStatus.ONLINE:
        return 1; // 在线
      case SatelliteStatus.OFFLINE:
        return 0; // 离线
      case SatelliteStatus.ALERT:
        return 2; // 已注入
      default:
        return 0; // 默认离线
    }
  }
  
  // 辅助方法：从轨道类型获取卫星类型
  private getSatelliteTypeFromOrbitType(orbitType: string): number {
    switch (orbitType) {
      case OrbitType.LEO:
        return 0; // 低轨
      case OrbitType.MEO:
        return 1; // 中轨
      case OrbitType.GEO:
      case OrbitType.SGO:
        return 2; // 近轨/静轨
      default:
        return 0; // 默认低轨
    }
  }
  
  // 辅助方法：找到最接近鼠标位置的卫星
  private findClosestSatellite(mouse: Vector2, camera: PerspectiveCamera): Sprite | null {
    if (this.satellites.size === 0) return null;
    // 将所有卫星转换为屏幕坐标
    const allSatellites = Array.from(this.satellites.values());
    const screenPositions: {satellite: Sprite, x: number, y: number, distance: number, id: string}[] = [];
    const vector = new Vector3();
    const width = this.domElement.clientWidth;
    const height = this.domElement.clientHeight;
    
    // 计算鼠标在屏幕上的绝对位置
    const mouseX = (mouse.x * 0.5 + 0.5) * width;
    const mouseY = (-mouse.y * 0.5 + 0.5) * height; 
    console.log("鼠标屏幕位置:", mouseX, mouseY);
    // 计算每个卫星在屏幕上的位置
    for (const satellite of allSatellites) {
      // 确保卫星有有效的userData
      if (!satellite.userData || !satellite.userData.id) continue;
      vector.copy(satellite.position);
      vector.project(camera);
      const x = (vector.x * 0.5 + 0.5) * width;
      const y = (-vector.y * 0.5 + 0.5) * height;
      // 计算与鼠标位置的距离
      const dx = x - mouseX;
      const dy = y - mouseY;
      const distance = Math.sqrt(dx * dx + dy * dy);
      screenPositions.push({
        satellite, 
        x, 
        y, 
        distance,
        id: satellite.userData.id
      });
    }
    
    // 对距离排序
    screenPositions.sort((a, b) => a.distance - b.distance);
    if (screenPositions.length > 0) {
      // 输出最近的3个卫星信息，帮助调试
      const closest = screenPositions.slice(0, Math.min(3, screenPositions.length));
      console.log("最近的卫星:", closest.map(p => ({
        id: p.id,
        distance: Math.round(p.distance),
        position: `(${Math.round(p.x)}, ${Math.round(p.y)})`
      })));
      
      // 返回最近的卫星，如果距离小于阈值
      // 增加阈值到80像素，使点击更容易
      if (closest[0].distance < 80) {
        console.log(`选中最近的卫星: ID=${closest[0].id}, 距离=${Math.round(closest[0].distance)}px`);
        return closest[0].satellite;
      } else {
        console.log(`最近的卫星 ID=${closest[0].id} 距离太远: ${Math.round(closest[0].distance)}px > 80px`);
      }
    }
    
    return null;
  }
  
  // 添加清理方法
  public dispose() {
    // 移除事件监听器
    this.domElement.removeEventListener('mousemove', this.onMouseMove.bind(this));
    this.domElement.removeEventListener('click', this.onMouseClick.bind(this));   
    // 移除信息面板
    if (this.infoPanel && this.infoPanel.parentNode) {
      this.infoPanel.parentNode.removeChild(this.infoPanel);
    }
    this.infoPanel = null;
    this.hoveredSatellite = null;
  }
}